<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  
  <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1">
  <meta name="format-detection" content="telephone=no">
  <title>客服系统</title>
  <script src="//cdn.bootcss.com/es6-promise/4.1.0/es6-promise.min.js"></script>
  <!-- <script src="https://og6593g2z.qnssl.com/fundebug.0.0.8.min.js" apikey="2bce51528f59c0ff0799b63562df5279635d40c84fbf332dc9ab3c68a4b00a31"></script> -->
  <!--<script type="text/javascript" src="//www.wsloan.com/js/checkOpenIp.js"></script>-->

  <!-- CHAT ASS -->
  <!-- <script charset="utf-8" type="text/javascript" src="https://g.alicdn.com/aliww/h5.openim.kit/0.4.0/scripts/pckit.js"></script> -->
  <script src="https://g.alicdn.com/aliww/??h5.imsdk/2.2.7/scripts/yw/wsdk.js,h5.openim.kit/0.4.0/scripts/kit.js" charset="utf-8"></script>
  <script src="//static.wsloan.com/Script/es6-promise.min.js"></script>
  
  <link rel="stylesheet" href="https://g.alicdn.com/aliww/h5.openim.kit/0.4.0/styles/pckit.css" id="wkit-pckit-css">

  <!--  -->
  <script>
    window.Promise = window.Promise || ES6Promise;

  </script>
  <style>
    /*以下开关样式均必须在页面上进行初始化*/
    #dragSwitch{
      display:none;
      position:absolute;
      z-index:200;
      top:60px;
      right:0;
      width:160px;
      height:40px;
      font-size:14px;
      background: #e9e9e9;
      border: 1px solid #444;
      border-radius: 5px;
      box-shadow: 0 1px 3px 2px #666;
      cursor:pointer;
    }
    #drag {
      visibility:hidden;
      position: absolute;
      top: calc(50% - 40vh);
      left: 0;
      z-index: 201;
      width: 100%;
      height: 80vh;
      background: #e9e9e9;
      border: 1px solid #444;
      border-radius: 5px;
      box-shadow: 0 1px 3px 2px #666;
    }
    #chat {
      position:absolute;                                                                                            
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
    }

  </style>
</head>

<body>
  <div id="app"></div>
  <!-- <button id="dragSwitch">客服聊天室</button> -->
  <div id="drag">
    <div class="title">
      <h2>聊天室</h2>
      <div>
        <a class="max el-icon-d-caret" href="javascript:;" title="最大化"></a>
        <a class="revert el-icon-caret-bottom" href="javascript:;" title="还原"></a>
        <a class="close el-icon-circle-cross" href="javascript:;" title="关闭"></a>
      </div>
    </div>
    <div class="resizeL"></div>
    <div class="resizeT"></div>
    <div class="resizeR"></div>
    <div class="resizeB"></div>
    <div class="resizeLT"></div>
    <div class="resizeTR"></div>
    <div class="resizeBR"></div>
    <div class="resizeLB"></div>
    <div class="content">
      <div id="chat">
        <div id="kefuBody" class="keBody" style="display: none">
          <div class="kePublic">
            <!--效果html开始-->
            <div class="content">
              <div class="chatBox">
                <div class="chatLeft">
                  <div class="chat03">
                    <div class="chat03_title">
                      <div class="chat03_title_t ct_3">
                        <label>个人聊天</label>
                      </div>
                      <div class="chat05_title_t ct_5">
                        <label>群聊</label>
                      </div>
                      <div class="chat06_title_t ct_6">
                        <label>专属客户</label>
                      </div>
                      <div class="chat04_title_t ct_4">
                        <label>通讯录</label>
                      </div>
                    </div>
                    <div class="chat03_content">
                      <!-- haoyoulist -->
                      <ul id="haoyoulist" class="personal" style="overflow: auto; height: 750px;">
                      </ul>
                      <!--  -->
                      <!-- grouplist -->
                      <ul id="grouplist" class="groupchat" style="display: none; overflow: auto; height: 750px;">
                      </ul>
                      <!--  -->
                      <!-- khinfolist -->
                      <ul id="khinfolist" class="personal" style="display: none; overflow: auto; height: 750px;">
                        <div style="height: 30px; width: 100%; border-bottom: solid 1px; text-align: center;">
                          <input type="text" id="khSearchKey" />
                          <input type="button" id="khinfoSearch" value="查询" />
                        </div>
                      </ul>
                      <!--  -->
                      <!-- maillist -->
                      <ul id="maillist" class="personal" style="display: none; overflow: auto; height: 750px;">
                      </ul>
                      <!--  -->
                    </div>
                  </div>
                </div>
                <div class="chatMiddle">
                  <div class="chat01_title">
                    <ul class="talkTo">
                      <li><a href="javascript:;"></a></li>
                    </ul>
                    <a class="close_btn" href="javascript:;"></a>
                  </div>
                  <div class="chat01" id="chatContentNav">
                    <div id="J_demo" class="chat01_content" style="width: 100%;"></div>
                  </div>
                  <div class="chat02" style="display: none;">
                    <div class="chat02_title">
                      <a class="chat02_title_btn ctb01" id="myEmotTrigger" href="javascript:;">表情</a>
                      <a class="chat02_title_btn ctb02" id="myImageTrigger" href="javascript:;" title="选择图片">图片</a>
                      <input type="file" id="J_fileInput" style="display: none;" accept="image/*" />
                      <div class="my-soft-input">
                        <div id="myEmotBox" style="display: none"></div>
                      </div>
                    </div>
                    <div class="chat02_content">
                      <textarea id="textarea"></textarea>
                    </div>
                    <div class="chat02_bar">
                      <ul>
                        <li style="right: 5px; top: 5px;">
                          <a href="javascript:;"><img src="img/send_btn.jpg" width="0" height="0"></a>
                        </li>
                      </ul>
                    </div>
                  </div>
                </div>

                <div class="chatRight">
                  <div class="chat03">
                    <div class="chat03_title">
                      <div class="chat07_title_t ct2_3">
                        <label>资料</label>
                      </div>
                      <div class="chat08_title_t ct2_5">
                        <label>标签</label>
                      </div>
                      <div class="chat09_title_t ct2_4">
                        <label>常见问题</label>
                      </div>
                    </div>
                    <div>
                      <div id="userdata" style="overflow: auto; height: 750px;">
                        <table width="100%" border="0" cellspacing="10" cellpadding="0">
                          <tr>
                            <td width="25%" height="25" align="right" class="tabtd2">用户id：</td>
                            <td width="75%" height="25" class="tabtd userdata_id"></td>
                          </tr>
                          <tr>
                            <td height="25" align="right" class="tabtd2">用户名：</td>
                            <td height="25" class="tabtd userdata_userno"></td>
                          </tr>
                          <tr>
                            <td height="25" align="right" class="tabtd2">姓名：</td>
                            <td height="25" class="tabtd userdata_name"></td>
                          </tr>
                          <tr>
                            <td height="25" align="right" class="tabtd2">性别：</td>
                            <td height="25" class="tabtd userdata_sex"></td>
                          </tr>
                          <tr>
                            <td height="25" align="right" class="tabtd2">开户情况：</td>
                            <td height="25" class="tabtd userdata_kaihuqk"></td>
                          </tr>
                          <tr>
                            <td height="25" align="right" class="tabtd2">VIP等级：</td>
                            <td height="25" class="tabtd userdata_vip"></td>
                          </tr>
                          <tr>
                            <td height="25" align="right" class="tabtd2">手机号码：</td>
                            <td height="25" class="tabtd userdata_tel"></td>
                          </tr>
                          <tr>
                            <td height="25" align="right" class="tabtd2">地区：</td>
                            <td height="25" class="tabtd userdata_city"></td>
                          </tr>
                          <tr>
                            <td height="25" align="right" class="tabtd2">银行卡号码：</td>
                            <td height="25" class="tabtd userdata_bank"></td>
                          </tr>
                          <tr>
                            <td height="25" align="right" class="tabtd2">账户余额：</td>
                            <td height="25" class="tabtd userdata_zhye"></td>
                          </tr>
                          <tr>
                            <td height="25" align="right" class="tabtd2">待收金额：</td>
                            <td height="25" class="tabtd userdata_dsje"></td>
                          </tr>
                          <tr>
                            <td height="25" align="right" class="tabtd2">待收利息：</td>
                            <td height="25" class="tabtd userdata_dslx"></td>
                          </tr>
                        </table>
                      </div>
                      <div id="usertag" style="overflow: auto; height: 750px; display: none;">
                        <iframe width="100%" frameborder="0" marginheight="0" marginwidth="0" scrolling="auto" name="nr" id="nr"></iframe>
                      </div>
                      <div id="problem" style="overflow: auto; height: 750px; display: none;">
                        <div class="problem_li">
                          <div class="chat03_name">
                            <input id="problemSearchkey" type="text" property="搜索" />
                            <button onclick="searchProblem()">搜索</button>
                          </div>
                        </div>
                        <ul id="problem_ul">
                        </ul>
                      </div>
                    </div>
                  </div>
                </div>
                <div style="clear: both;">
                </div>
              </div>
            </div>
            <!--效果html结束-->
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- built files will be auto injected -->
</body>
<!-- <script src="http://wechatfe.github.io/vconsole/lib/vconsole.min.js?v=2.3.1"></script> -->
<script>
  // 拖拽框的效果
  (function () {
    /*-------------------------- +
     获取id, class, tagName
     +-------------------------- */
    var get = {
      byId: function (id) {
        return typeof id === "string" ? document.getElementById(id) : id
      },
      byClass: function (sClass, oParent) {
        var aClass = [];
        var reClass = new RegExp("(^| )" + sClass + "( |$)");
        var aElem = this.byTagName("*", oParent);
        for (var i = 0; i < aElem.length; i++) reClass.test(aElem[i].className) && aClass.push(aElem[i]);
        return aClass
      },
      byTagName: function (elem, obj) {
        return (obj || document).getElementsByTagName(elem)
      }
    };
    var dragMinWidth = 1240;
    var dragMinHeight = 600;
    /*-------------------------- +
     拖拽函数
     +-------------------------- */
    function drag(oDrag, handle) {
      var disX = disY = 0;
      // var oMin = get.byClass("min", oDrag)[0];
      var oMax = get.byClass("max", oDrag)[0];
      var oRevert = get.byClass("revert", oDrag)[0];
      var oClose = get.byClass("close", oDrag)[0];
      handle = handle || oDrag;
      handle.style.cursor = "move";
      handle.onmousedown = function (event) {
        var event = event || window.event;
        disX = event.clientX - oDrag.offsetLeft;
        disY = event.clientY - oDrag.offsetTop;
        document.onmousemove = function (event) {
          var event = event || window.event;
          var iL = event.clientX - disX;
          var iT = event.clientY - disY;
          var maxL = document.documentElement.clientWidth - oDrag.offsetWidth;
          var maxT = document.documentElement.clientHeight - oDrag.offsetHeight;
          iL <= 0 && (iL = 0);
          iT <= 0 && (iT = 0);
          iL >= maxL && (iL = maxL);
          iT >= maxT && (iT = maxT);
          oDrag.style.left = iL + "px";
          oDrag.style.top = iT + "px";
          return false
        };
        document.onmouseup = function () {
          document.onmousemove = null;
          document.onmouseup = null;
          this.releaseCapture && this.releaseCapture()
        };
        this.setCapture && this.setCapture();
        return false
      };
      //最大化按钮
      oMax.onclick = function () {
        $('#drag').css({
          left:0,
          top:0,
          width:'100%',
          height:'100%',
        });
        $(this).hide().siblings('.revert').show();
      };
      //还原按钮
      oRevert.onclick = function () {
        $('#drag').css({
          left:0,
          top:'calc(50% - 40vh)',
          width:'100%',
          height:'80vh',
        });
        $(this).hide().siblings('.max').show();
      };
      //最小化按钮
      oClose.onclick = function () {
        $('#drag').css('visibility','hidden');
        $('#dragSwitch').show();
      };
      //阻止冒泡
      oMax.onmousedown = oClose.onmousedown = function (event) {
        this.onfocus = function () {
          this.blur()
        };
        (event || window.event).cancelBubble = true
      };
    }
    /*-------------------------- +
     改变大小函数
     +-------------------------- */
    function resize(oParent, handle, isLeft, isTop, lockX, lockY) {
      handle.onmousedown = function (event) {
        var event = event || window.event;
        var disX = event.clientX - handle.offsetLeft;
        var disY = event.clientY - handle.offsetTop;
        var iParentTop = oParent.offsetTop;
        var iParentLeft = oParent.offsetLeft;
        var iParentWidth = oParent.offsetWidth;
        var iParentHeight = oParent.offsetHeight;
        document.onmousemove = function (event) {
          var event = event || window.event;
          var iL = event.clientX - disX;
          var iT = event.clientY - disY;
          var maxW = document.documentElement.clientWidth - oParent.offsetLeft - 2;
          var maxH = document.documentElement.clientHeight - oParent.offsetTop - 2;
          var iW = isLeft ? iParentWidth - iL : handle.offsetWidth + iL;
          var iH = isTop ? iParentHeight - iT : handle.offsetHeight + iT;
          isLeft && (oParent.style.left = iParentLeft + iL + "px");
          isTop && (oParent.style.top = iParentTop + iT + "px");
          iW < dragMinWidth && (iW = dragMinWidth);
          iW > maxW && (iW = maxW);
          lockX || (oParent.style.width = iW + "px");
          iH < dragMinHeight && (iH = dragMinHeight);
          iH > maxH && (iH = maxH);
          lockY || (oParent.style.height = iH + "px");
          if ((isLeft && iW == dragMinWidth) || (isTop && iH == dragMinHeight)) document.onmousemove = null;
          return false;
        };
        document.onmouseup = function () {
          document.onmousemove = null;
          document.onmouseup = null;
        };
        return false;
      }
    };
    // window.onload = window.onresize = function ()
    // {
    function initDrag() {
      var oDrag = document.getElementById("drag");
      var oTitle = get.byClass("title", oDrag)[0];
      var oL = get.byClass("resizeL", oDrag)[0];
      var oT = get.byClass("resizeT", oDrag)[0];
      var oR = get.byClass("resizeR", oDrag)[0];
      var oB = get.byClass("resizeB", oDrag)[0];
      var oLT = get.byClass("resizeLT", oDrag)[0];
      var oTR = get.byClass("resizeTR", oDrag)[0];
      var oBR = get.byClass("resizeBR", oDrag)[0];
      var oLB = get.byClass("resizeLB", oDrag)[0];
      drag(oDrag, oTitle);
      //四角
      resize(oDrag, oLT, true, true, false, false);
      resize(oDrag, oTR, false, true, false, false);
      resize(oDrag, oBR, false, false, false, false);
      resize(oDrag, oLB, true, false, false, false);
      //四边
      resize(oDrag, oL, true, false, false, true);
      resize(oDrag, oT, false, true, true, false);
      resize(oDrag, oR, false, false, false, true);
      resize(oDrag, oB, false, false, true, false);

      // 初始化客服聊天室的开关按钮
      // $('#dragSwitch').click(function(){
      //   if(!$('#chat').hasClass('init')){
      //     main(isLogin.kfId, isLogin.token);
      //   }
      //   $('#drag').css('visibility','visible');
      //   $(this).hide();
        
      // });
    }
    initDrag();
    // }
  }());

  // 聊天室
  var isLogin = {
    _value: 0,
    kfId: null,
    token: null
  };
  Object.defineProperty(isLogin, 'value', {
    // value:0,
    get: function () {
      return this._value
    },
    set: function (val) {
      if (val === 1) {
        // main();
        $('#dragSwitch').show();
      }
      this._value = val
      return
    }
  });
  function main(kfId,token) {
    // ## INITIALIZE
    window.__WSDK__POSTMESSAGE__DEBUG__ = true;
    // <%=dicjson%>
    var userlist = null;
    // <%=OSSManager.AliyunImagePath%>
    var picurl = null;
    var firstUid = 'guanjia';
    var userarray = [];
    var recentTribe = [];
    var Emot = null;
    var tribeid = '';
    var chatuserid = '';
    var nextkeys = new Map();
    var lastmsgid = '';
    var lasttribemsgid = '';
    var type = 0;
    var butid = 1;
    var wkit;

    // PARAMS FORM BACK
    var localUid = '';
    var localUser = null;
    var mailHtml = '';
    var appkey = '';
    var apppass = '';
    var appsecret = '';
    // var kfId = 10;
    // kfId = 17;
    var khpage = 1;
    var khpagesize = 100;
    var isInifkf = true;

    // END

    // 工具
    Date.prototype.format = function(fmt) {
      var o = {
          "M+" : this.getMonth()+1,                 //月份
          "d+" : this.getDate(),                    //日
          "h+" : this.getHours(),                   //小时
          "m+" : this.getMinutes(),                 //分
          "s+" : this.getSeconds(),                 //秒
          "q+" : Math.floor((this.getMonth()+3)/3), //季度
          "S"  : this.getMilliseconds()             //毫秒
      };
      if(/(y+)/.test(fmt)) {
              fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
      }
      for(var k in o) {
          if(new RegExp("("+ k +")").test(fmt)){
              fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
          }
      }
      return fmt;
    }

    var baseUrl = 'http://i.wsloan.com/';
    // utils
    function ajax(obj) {
      /*
        obj参数说明
        @param api 接口路径
        @param method 请求的类型
        @param async 请求是否异步
        @param data 接口请求参数
        @param success 请求成功的回调
        @param error 请求失败的回调
      **/
      // var innerUrl = 'http://36.7.138.114:5026/css';
      // var innerUrl = 'http://192.168.22.36:8080/css';
      var innerUrl = 'http://report.wsloan.com:8888/css';
      console.log('html:', token)
      $.ajax({
        url: (innerUrl + obj.api) || '',
        async: obj.async || true,
        type: obj.method || 'get',
        beforeSend: function(xhr) {
              // xhr.setRequestHeader("Authorization","eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoiMiIsInVuaXF1ZV9uYW1lIjp7ImlkIjoxMzk1LCJkdXR5IjpudWxsLCJpc0FkbWluIjpudWxsLCJwb3dlciI6MiwidXNlcnRlbCI6IjM2MjQiLCJwc2QiOiIxMjM0NTYiLCJvbGRJZCI6bnVsbCwib2xkR3JvdXBJZCI6MTA0LCJleHRlbk51bWJlck5ldyI6IjgxMDAyIiwiZlBpZCI6IjEzOTUiLCJwYXNzd29yZCI6IjEyMzQ1IiwidXNlckdyb3VwIjoi5Lia5Yqh57uEIiwiZGVwYXJ0bWVudCI6IuWuouacjeS4reW_gyIsInVzZXJOYW1lIjoi5YC854-t5a6i5pyNQSIsInVzZXJHcm91cElkIjoxMDR9LCJ1c2VyaWQiOiIxMzk1IiwiZXhwIjoxNTEzOTU1MTk4LCJuYmYiOjE1MTM5MTE5OTh9.Ovw9ooZyEX5bYJZ99DpPaug7_aAn6EWmcUSWjeH2ZUc");
              xhr.setRequestHeader("Authorization", token);
        },
        data: obj.data || {},
        dataType: 'json',
        success: obj.success || function () {},
        error: obj.error || function () {},
      })
    }

    // entry to access
    function entry() {
      
      ajax({
        api: '/APPapi/findIMid.do',
        method: 'get',
        data: {
          kfid: kfId
        },
        success: function (data) {
          if (data.state === 0 && data.content) {
            localUid = data.content + '';
            // localUid = '2019';
            init();
            return
          }
          
          alert('客服id'+ kfId +' 未能绑定聊天室功能，请联系技术人员');
        },
        error: function (e) {
          console.log('findIMid(e):', e);
        }
      });
    }

    // 用来控制异步流程
    var asyncCount = {
      _value: 0
    };
    Object.defineProperty(asyncCount, 'value', {
      get: function () {
        return this._value;
      },
      set: function (val) {
        this._value = val;
        if (val === 3) {
          bootstrap();
          return
        }
      }
    });

    function init() {
      // if (!localUid) {
      //   document.getElementById("kefuText").style.display = "block";
      //   document.getElementById("kefuBody").style.display = "none";
      // } else {
      // 获取基本信息
      // getUserInfo();
      // getFriendsInfo();
      // getConfigInfo();
      // }
      if (localUid) {
        // 获取基本信息
        getUserInfo();
        getFriendsInfo();
        getConfigInfo();
      }
    }


    // 启动函数
    function bootstrap() {
      // document.getElementById("kefuText").style.display = "none";
      document.getElementById("kefuBody").style.display = "block";
      $('#chat').addClass('init');
      function htsHide() {
        $(".hovertreeshowlayer img").remove();
        $(".hovertreeshowcover").hide();
        $(".hovertreeshowlayer").hide();
      }
      $("#chatContentNav").on("click", ".tribemsgimage", function () {
        if ($(".hovertreeshowcover").length == 0) {
          $("body").append("<div class='hovertreeshowcover'></div>").append(
            "<div class='hovertreeshowlayer'></div>")

          $(".hovertreeshowcover").on("click", function () {
            htsHide();
          })
          $(".hovertreeshowlayer").on("click", function () {
            htsHide();
          })
        } else {
          $(".hovertreeshowcover").show();
          $(".hovertreeshowlayer").show();
        }
        $(".hovertreeshowlayer").append('<img style="height:800px;" src="' + this.src + '"/>')
      });

      $("#myImageTrigger").on("click", function () {
        $("#J_fileInput").click();
      });

      $("#khinfolist").scroll(function () {
        var $this = $(this),
          viewH = $(this).height(), //可见高度
          contentH = $(this).get(0).scrollHeight, //内容高度
          scrollTop = $(this).scrollTop(); //滚动高度
        //if(contentH - viewH - scrollTop <= 100) { //到达底部100px时,加载新内容
        if (scrollTop / (contentH - viewH) >= 0.95) { //到达底部100px时,加载新内容
          if (isInifkf) {
            initKhInfoList();
          }
        }
      });


      // fileInput
      var fileInput = document.getElementById('J_fileInput');
      fileInput.onchange = function () {
        var e = new Date(),
          f = "";
        WKIT.Conn.sdk.Plugin.Image.upload({
          target: fileInput,
          success: function (data) {
            var msg = '<img class="tribemsgimage" style="height:200px;" src="' + data.data.base64Str + ' "/>';
            WKIT.Conn.sdk.Tribe.sendMsg({
              tid: tribeid,
              msg: data.data.url,
              msgType: 1,
              success: function (msgdata) {
                var userimg = picurl + 'yhtx/' + localUser.cYhtx;
                var nickname = localUser.cNichen;
                f += e.getFullYear() + "-", f += e.getMonth() + 1 + "-", f += e.getDate() + "  ", f += e.getHours() +
                  ":", f += e.getMinutes() + ":", f += e.getSeconds();

                var i = '<div class="message clearfix"><div class="user-logo"><img src="' + userimg +
                  '"/>' + '</div>' +
                  '<div class="wrap-text">' + '<h5 class="clearfix">' + nickname + '</h5>' + '<div>' +
                  msg + '</div>' +
                  '</div>' + '<div class="wrap-ri">' + '<div clsss="clearfix"><span>' + f +
                  '</span></div>' + '</div>' +
                  '<div style="clear:both;"></div>' + '</div>';
                $("#Tribe_" + tribeid).append(i), $("#Tribe_" + tribeid).scrollTop($("#Tribe_" + tribeid)[
                  0].scrollHeight);

                console.log('发送群消息成功', msgdata);
              },
              error: function (msgerror) {
                console.log('发送群消息失败', msgerror);
              }
            });

            console.log('上传成功', data);
          },
          error: function (error) {
            console.log('上传失败', error);
          }
        });
      }
      //==
      if (mailHtml) {
        $('#maillist').html(mailHtml);
      }
      setTimeout(initWkit, 500);
      setTimeout(Msg, 2000);
      setTimeout(emjor, 2000);
      setTimeout(initKhInfoList, 2000);
      // initWkit();
      // Msg();
      // emjor();
      //
      // H5弹窗

    }

    var NotificationHandler = {
            isNotificationSupported: 'Notification' in window,
            isPermissionGranted: function () {
                return Notification.permission === 'granted';
            },
            requestPermission: function () {
                if (!this.isNotificationSupported) {
                    console.log('the current browser does not support Notification API');
                    return;
                }

                Notification.requestPermission(function (status) {
                    //status是授权状态，如果用户允许显示桌面通知，则status为'granted'
                    console.log('status: ' + status);

                    //permission只读属性
                    var permission = Notification.permission;
                    //default 用户没有接收或拒绝授权 不能显示通知
                    //granted 用户接受授权 允许显示通知
                    //denied  用户拒绝授权 不允许显示通知

                    console.log('permission: ' + permission);
                });
            },
            showNotification: function (msgcontent) {
                if (!this.isNotificationSupported) {
                    console.log('the current browser does not support Notification API');
                    return;
                }
                if (!this.isPermissionGranted()) {
                    console.log('the current page has not been granted for notification');
                    return;
                }

                var n = new Notification("您好, 您收到一条消息", {
                    icon: 'img/im_msg.png',
                    body: msgcontent
                });

                //onshow函数在消息框显示时会被调用
                //可以做一些数据记录及定时操作等
                n.onshow = function () {
                    console.log('notification shows up');
                    //5秒后关闭消息框
                    setTimeout(function () {
                        n.close();
                    }, 5000);
                };

                //消息框被点击时被调用
                //可以打开相关的视图，同时关闭该消息框等操作
                n.onclick = function () {
                    alert('open the associated view');
                    //opening the view...
                    n.close();
                };

                //当有错误发生时会onerror函数会被调用
                //如果没有granted授权，创建Notification对象实例时，也会执行onerror函数
                n.onerror = function () {
                    console.log('notification encounters an error');
                    //do something useful
                };

                //一个消息框关闭时onclose函数会被调用
                n.onclose = function () {
                    console.log('notification is closed');
                    //do something useful
                };
            }
        };

    //
    function newMessage(type) {
      var audiosrc = "";
      if (type == 0) {
        audiosrc = baseUrl + "w6h8y3_n7s4d/mp3/chat_ding.wav";
      } else {
        audiosrc = baseUrl + "w6h8y3_n7s4d/mp3/tribe_ding.mp3";
      }
      var borswer = window.navigator.userAgent.toLowerCase();
      if (borswer.indexOf("ie") >= 0) {
        //IE内核浏览器
        var strEmbed = '<embed name="embedPlay" src="' + audiosrc +
          '" autostart="true" hidden="true" loop="false"></embed>';
        if ($("body").find("embed").length <= 0)
          $("body").append(strEmbed);
        var embed = document.embedPlay;

        //浏览器不支持 audion，则使用 embed 播放
        embed.volume = 100;
        //embed.play();这个不需要
      } else {
        //非IE内核浏览器
        var strAudio = '<audio id="audioPlay" src="' + audiosrc + '" hidden="true">';
        if ($("body").find("audio").length <= 0)
          $("body").append(strAudio);
        var audio = document.getElementById("audioPlay");

        //浏览器支持 audion
        audio.play();
      }
    }

    var a = 3,
      b = "img/head/2024.jpg",
      c = "img/head/2015.jpg",
      d = "\u738b\u65ed";
    var amrid = 1;

    function initWkit() {
      var suffix = localUser.cYhtx || ''
      wkit = WKIT.init({
        uid: localUid,
        appkey: appkey,
        credential: apppass,
        touid: firstUid,
        container: document.getElementById("J_demo"),
        avatar: picurl + "yhtx/" + suffix,
        onAudioReceived: function (content) {
          // content为语音的地址
          // 返回一个要显示语音的html字符串
          // 点击播放等操作请自己实现
          console.log('received')
          var str = '<audio id="audio_amr_' + amrid + '" src=""  controls="controls" preload="none"></audio>';
          // 延迟调用后台接口将amr转MP3
          setTimeout('downAmr("audio_amr_' + amrid + '","' + content + '")', 100);
          amrid += 1;
          return str;
        },
        onMsgSent: function (a, b) {
          var msg = a.msgs[0];
          var kfid = msg.from.substring(8);
          var touid = msg.to.substring(8);
          console.log('onMsgSent:', a, b)
          saveChatHis(kfid, touid, '', msg.msg, msg.time, 0);
          //a ? 1001 == a.code && this.reLoginCount <= 3 ? wkit.login(this.sdkOpts) : this.toast("消息发送失败, 请重试") : (this.renderChatMsg([b]), this.UI.textarea.value = "", this.opts.onMsgSent && this.opts.onMsgSent({ msgs: [b] }))
        }
      });
      $(".talkTo a").text(firstUid);
    }

    function downAmr(id, content) {
      ajax({
        method: 'post',
        api: '/APPapi/uploadAudio.do',
        data: {
          amrurl: content
        },
        success: function (data) {
          console.log('downAmr:', data)
          var audio = document.getElementById(id);
          audio.src = baseUrl + "/w6h8y3_n7s4d/MyDownloadFile/mp3/" + data.msg;
        }
      });
    }

    function Msg() {
      // 获取最近的联系人
      WKIT.Conn.sdk.Base.getRecentContact({
        count: 10,
        success: function (data) {
          console.log('WKIT.Conn.sdk.Base:', data)
          data = data.data;
          var list = data.cnts,
            type = '';
          var count = 0;
          list.forEach(function (item) {
            if (!document.getElementById("hyls_" + item.uid.substring(8))) {
              if (count == 0)
                firstUid = item.uid.substring(8);
              var jshy = userlist['' + item.uid.substring(8) + ''];
              var userimg = picurl + "yhtx/no.jpg";
              var nickname = item.uid.substring(8);
              if (jshy != undefined) {
                userimg = picurl + "yhtx/" + jshy.cHyYhtx;
                nickname = jshy.cHyNichen;
              }
              var hyli = '<li>' +
                '<label class="online" ></label>' +
                '<a href="javascript:;">' +
                '<img src="' + userimg + '" />' +
                '</a>' +
                '<a href="javascript:;" class="chat03_name" data-id="' + item.uid.substring(8) + '" >' +
                nickname + ' - ' + item.uid.substring(8) +'</a>' +
                '<div class="nav-counter" id="hyls_' + item.uid.substring(8) +
                '" style="display:none;">0</div></li>';
              $("#haoyoulist").append(hyli);
              userarray.push(item);
              count++;
            }
          });
        },
        error: function (error) {
          console.log('获取最近联系人及最后一条消息内容失败', error);
        }
      });

      // 获取群列表
      WKIT.Conn.sdk.Tribe.getTribeList({
        tribeTypes: [0, 1, 2],
        success: function (data) {
          console.log('获取群列表成功', data);
          var list = data.data;
          list.forEach(function (item) {
            var liid = "TribeLi_" + item.tid;
            if (!document.getElementById(liid)) {
              var tribeli = '<li id="' + liid + '">' +
                '<label class="online" >' +
                '</label>' +
                '<a href="javascript:;">' +
                '<img src="' + item.icon +
                '"></a><a href="javascript:;" class="chat03_name" data-id="' + item.tid + '">' + item.name +
                '</a>' +
                '<div class="nav-counter" id="tribels_' + item.tid +
                '" style="display:none;">0</div></li>';

              $("#grouplist").append(tribeli);
              var tribecontent = '<div id="Tribe_' + item.tid +
                '" class="chat01_content1" style="width:100%;display:none;"></div>';
              $("#chatContentNav").append(tribecontent);
              nextkeys.put('key_' + tribeli, '');
            }
          });
        },
        error: function (error) {
          console.log('获取群列表失败', error);
        }
      });

      // 监听单聊信息
      WKIT.Conn.sdk.Event.on('CHAT.MSG_RECEIVED', function (data) {
        console.log('我能收到成功的单聊消息', data);
        newMessage(0);
        data = data.data;
        if (data.msgs[0].msgId == lastmsgid) {
          return;
        }
        lastmsgid = data.msgs[0].msgId;
        var fromuid = data.touid.substring(8);
        var kfid = data.uid.substring(8)
        if (!document.getElementById("hyls_" + fromuid)) {

          var jshy = userlist['' + fromuid + ''];
          var userimg = picurl + "yhtx/no.jpg";
          var nickname = fromuid;
          if (jshy != undefined) {
            userimg = picurl + "yhtx/" + jshy.cHyYhtx;
            nickname = jshy.cHyNichen;
          }
          var hyli = '<li>' +
            '<label class="online" >' +
            '</label>' +
            '<a href="javascript:;">' +
            '<img src="' + userimg + '" /></a><a href="javascript:;" class="chat03_name" data-id="' + fromuid +
            '">' + nickname + ' - '+ fromuid + '</a>' +
            '<div class="nav-counter" id="hyls_' + fromuid + '" style="display:none;">0</div></li>';
          $("#haoyoulist").append(hyli);
        } else {
          var count = Number($("#hyls_" + fromuid).text());
          count += 1;
          $("#hyls_" + fromuid).text(count);
          $("#hyls_" + fromuid).show();
          var li = $("#hyls_" + fromuid).parent()[0];
          var index = $("#chat .chat03_content #haoyoulist li").index(li);
          $('#chat .chat03_content #haoyoulist').prepend($('#chat ul li:eq(' + index + ')'));
        }
        saveChatHis(kfid, fromuid, data.msgs[0].msgId, data.msgs[0].msg, data.msgs[0].time, 1);
      });

      // 监听群聊信息
      WKIT.Conn.sdk.Event.on('TRIBE.MSG_RECEIVED', function (data) {
        console.log('我能收到成功的群聊消息', data);
        newMessage(1);
        data = data.data;
        if (data.msgs[0].msgId == lastmsgid) {
          return;
        }
        lasttribemsgid = data.msgs[0].msgId;
        var tid = data.touid;
        var fromuid = data.msgs[0].from.substring(8);
        if (!document.getElementById("tribels_" + tid)) {
          var item = null;
          var icon = "http://tpsrv.wws.taobao.com/webim/tribev6/tribeGetLogo.htm";
          var name = "群聊";
          WKIT.Conn.sdk.Tribe.getTribeInfo({
            tid: 'tid',
            success: function (data) {
              item = data.data;
              console.log('获取群信息成功', data);
            },
            error: function (error) {
              console.log('获取群信息失败', error);
            }
          });
          if (item != null) {
            icon = item.icon;
            name = item.name;
          }
          var liid = "TribeLi_" + tid;
          var tribeli = '<li id="' + liid + '">' +
            '<label class="online" >' +
            '</label>' +
            '<a href="javascript:;">' +
            '<img src="' + icon + '"></a><a href="javascript:;" class="chat03_name" data-id="' + tid + '">' +
            name + '</a>' +
            '<div class="nav-counter" id="tribels_' + tid + '" style="display:none;">0</div></li>';

          $("#grouplist").append(tribeli);
          var tribecontent = '<div id="Tribe_' + item.tid +
            '" class="chat01_content1" style="width:100%;display:none;"></div>';
          $("#chatContentNav").append(tribecontent);
        }

        var jshy = userlist['' + fromuid + ''];
        var userimg = picurl + "yhtx/no.jpg";
        var nickname = fromuid;
        if (jshy != undefined) {
          userimg = picurl + "yhtx/" + jshy.cHyYhtx;
          nickname = jshy.cHyNichen;
        }

        if (tribeid != tid || type != 1) {
          var count = Number($("#tribels_" + tid).text());
          count += 1;
          $("#tribels_" + tid).text(count);
          $("#tribels_" + tid).show();
        }

        var li = $("#tribels_" + tid).parent()[0];
        var index = $("#chat .chat03_content #grouplist li").index(li);
        $('#chat .chat03_content #grouplist').prepend($('.chat03_content #grouplist li:eq(' + index + ')'));

        var e = new Date(data.msgs[0].time),
          f = "";
        var msg = "";
        if (data.msgs[0].type != 1) {
          if (data.msgs[0].type == 0) {
            msg = ReplaceMsg(data.msgs[0].msg);
          } else if (data.msgs[0].type == 16) {
            var imgstr = 'http://ftsproxy.wangxin.taobao.com/fetch?uid=' + data.uid + '&ftsip=' + data.msgs[0].msg.ftsip +
              '&ftsport=' + data.msgs[0].msg.ftsport + '&ssession=' + data.msgs[0].msg.ssession + '&filesize=' +
              data.msgs[0].msg.filelen +
              '&filename=' + data.msgs[0].msg.filehash + data.msgs[0].msg.fileextend + '&thumbnail=2&width=' + data
              .msgs[0].msg.width + '&height=' + data.msgs[0].msg.height;
            msg = '<img class="tribemsgimage" style="height:200px;" src="' + imgstr + '" />';
          }
          f += e.getFullYear() + "-", f += e.getMonth() + 1 + "-", f += e.getDate() + "  ", f += e.getHours() + ":",
            f += e.getMinutes() + ":", f += e.getSeconds();

          var i = '<div class="message clearfix"><div class="user-logo"><img src="' + userimg + '"/>' + '</div>' +
            '<div class="wrap-text">' + '<h5 class="clearfix">' + nickname + '</h5>' + '<div>' + msg + '</div>' +
            '</div>' + '<div class="wrap-ri">' + '<div clsss="clearfix"><span>' + f + '</span></div>' + '</div>' +
            '<div style="clear:both;"></div>' + '</div>';
          $("#Tribe_" + tid).append(i), $("#Tribe_" + tid).scrollTop($("#Tribe_" + tid)[0].scrollHeight);
        }
      });

      setTimeout(initTribeMsg, 500);
      updateInfo(firstUid);
      changeuser(firstUid);
      initproblem('');
    }

    //PARTIAL
    // 转换表情格式的聊天内容
    function ReplaceMsg(str) {
      //return str.replace(/\/:.{1,3}/, function (word) {
      //    var tstr = word.substring(0, 5);
      //    return Emot.decode(tstr) + word.substring(5);
      //});
      return Emot.decode(str);
    }

    // 初始化未读的群聊天信息
    function initTribeMsg() {
      WKIT.Conn.sdk.Base.getUnreadMsgCount({
        count: 10,
        success: function (data) {
          var list = data.data;
          list.forEach(function (item) {
            if (item.contact.substring(0, 8) === 'chntribe') {
              recentTribe.push(item);
            } else {
              var uid = item.contact.substring(8);
              $("#hyls_" + uid).text(item.msgCount);
              $("#hyls_" + uid).show();
            }
          });
          // 群聊列表
          recentTribe.forEach(function (item) {
            var tid = item.contact.substring(8);
            var liid = "TribeLi_" + tid;
            if (!document.getElementById(liid)) {
              var tribeli = '<li id="' + liid + '>' +
                '<label class="online" >' +
                '</label>' +
                '<a href="javascript:;">' +
                '<img src="img/head/2013.jpg"></a><a href="javascript:;" class="chat03_name" data-id="' +
                tid + '">' + tid + '</a>' +
                '<div class="nav-counter" id="tribels_' + tid + '" style="display:none;">' + item.msgCount +
                '</div></li>';

              $("#grouplist").append(tribeli);
              var tribecontent = '<div id="Tribe_' + item.contact.substring(8) +
                '" class="chat01_content1" style="width:100%;display:none;"></div>';
              $("#chatContentNav").append(tribecontent);
              nextkeys.put('key_' + tid, '');
            } else {
              var count = Number($("#tribels_" + tid).text());
              count += item.msgCount;
              if (count > 0) {
                $("#tribels_" + tid).text(count);
                $("#tribels_" + tid).show();
                var li = $("#" + liid);
                var index = $("#chat .chat03_content #grouplist li").index(li);
                $('#chat .chat03_content #grouplist').prepend($('#chat .chat03_content #grouplist li:eq(' + index + ')'));
              }
            }
          });
          recentTribe.length && console.log('最近给我发消息的群', recentTribe);
        },
        error: function (error) {
          console.log('获取未读消息的条数失败', error);
        }
      });
    }
    // 初始化表情包
    function emjor() {
      var box = document.getElementById('myEmotBox'),
        isEmotInited = false,
        isEmotBoxShow = false,
        selemj = false;

      Emot = WKIT.Conn.sdk.Plugin.Emot;

      $("#myEmotTrigger").on("click", function () {
        if (!isEmotInited) {
          Emot.render({
            container: box,
            onEmotClick: emotClickHandler
          });
          isEmotInited = true;
        }
        if (isEmotBoxShow) {
          box.style.display = 'none';
        } else {
          box.style.display = 'block';
        }
        isEmotBoxShow = !isEmotBoxShow;
      });
      /**
       * 点击表情时的事件
       */
      var emotClickHandler = function (emotTitle) {
        textarea.value += emotTitle;
        if (isEmotBoxShow) {
          box.style.display = 'none';
        } else {
          box.style.display = 'block';
        }
        isEmotBoxShow = false;
      };
    }

    function sendMsg() {
      var e = new Date,
        f = "";
      f += e.getFullYear() + "-", f += e.getMonth() + 1 + "-", f += e.getDate() + "  ", f += e.getHours() + ":", f += e
        .getMinutes() + ":", f += e.getSeconds();
      var g = $("#textarea").val();
      if (g == "") {
        alert("\u8bf7\u8f93\u5165\u804a\u5929\u5185\u5bb9!");
        return;
      }
      var encodeMsg = Emot.htmlEncode(g);
      var decodeMsg = Emot.decode(encodeMsg);

      var userimg = picurl + "yhtx/" + localUser.cYhtx;
      var nickname = localUser.cNichen;

      var i = '<div class="message clearfix"><div class="user-logo"><img src="' + userimg + '" />' + '</div>' +
        '<div class="wrap-text">' + '<h5 class="clearfix">' + nickname + '</h5>' + '<div>' + decodeMsg + '</div>' +
        '</div>' + '<div class="wrap-ri">' + '<div clsss="clearfix"><span>' + f + '</span></div>' + '</div>' +
        '<div style="clear:both;"></div>' + '</div>';
      null != decodeMsg && "" != decodeMsg ? ($("#Tribe_" + tribeid).append(i),
          // $("#Tribe_" + tribeid).scrollTop($("#Tribe_" + tribeid)[0].scrollHeight), $("#textarea").val(""), message()) :
          $("#Tribe_" + tribeid).scrollTop($("#Tribe_" + tribeid)[0].scrollHeight), $("#textarea").val("")) :
        alert("\u8bf7\u8f93\u5165\u804a\u5929\u5185\u5bb9!")

      WKIT.Conn.sdk.Tribe.sendMsg({
        tid: tribeid,
        msg: encodeMsg,
        success: function (data) {
          console.log('发送群消息成功', data);
        },
        error: function (error) {
          console.log('发送群消息失败', error);
        }
      });
    }

    /**
     * 渲染消息
     */
    function renderMsg(msg) {
      var div = document.createElement('div');
      div.innerHTML = msg;
      return div;
    }

    function changeuser(uid) {
      if (chatuserid == uid) return;
      // return;
      chatuserid = uid;
      var userimg = picurl + "yhtx/no.jpg";
      $("#J_demo").show().siblings().hide();
      if (!document.getElementById("hyls_" + uid)) {
        var jshy = userlist['' + uid + ''];
        var nickname = uid;
        if (jshy != undefined) {
          userimg = picurl + "yhtx/" + jshy.cHyYhtx;
          nickname = jshy.cHyNichen;
        }
        var hyli = '<li>' +
          '<label class="online" >' +
          '</label>' +
          '<a href="javascript:;">' +
          '<img src="' + userimg + '" /></a><a href="javascript:;" class="chat03_name" data-id="' + uid + '">' +
          nickname + ' - '+ uid + '</a>' +
          '<div class="nav-counter" id="hyls_' + uid + '" style="display:none;">0</div></li>';
        $("#haoyoulist").prepend(hyli);
      }
      $("#hyls_" + uid).text(0);
      $("#hyls_" + uid).hide();
      $("#chat .chat02").hide();
      WKIT.switchTouid({
        touid: uid,
        toAvatar: userimg
      });
      WKIT.Conn.sdk.Chat.setReadState({
        touid: uid,
        timestamp: Math.floor((+new Date()) / 1000),
        success: function (data) {
          console.log('set read state success', data);
        },
        error: function (error) {
          console.log('set read state fail', error);
        }
      });

      var li = $("#hyls_" + uid).parent()[0];
      var index = $("#chat  .chat03_content #haoyoulist li").index(li);
      $('#chat .chat03_content #haoyoulist').prepend($('#chat ul li:eq(' + index + ')'));
      updateInfo(uid);
      changeUserTag(uid);
    }

    //
    function updateInfo(uid) {
      // var jshy = undefined;
      ajax({
        method: 'post',
        api: '/APPapi/userinfo.do',
        async: false,
        data: {
          fuid: localUid,
          fhyid: uid
        },
        success: function (data) {
          if (data.state === 0)
            var jshy = data.content;
          if (jshy) {
            $("#userdata .userdata_id").text(jshy.fHyid);
            $("#userdata .userdata_userno").text(jshy.cU_ser);
            $("#userdata .userdata_name").text(jshy.cName);
            $("#userdata .userdata_sex").text(jshy.cSex);
            if (jshy.UsrCustId == null) {
              $("#userdata .userdata_kaihuqk").text("未开户");
            } else {
              $("#userdata .userdata_kaihuqk").text("已开户");
            }
            $("#userdata .userdata_vip").text(jshy.fVipLev);
            $("#userdata .userdata_tel").text(jshy.cMtel);
            $("#userdata .userdata_city").text(jshy.cShen + " - " + jshy.cShi);
            $("#userdata .userdata_bank").text(jshy.cKhyh + " - " + jshy.cYhkh);
            $("#userdata .userdata_zhye").text(jshy.fSjje);
            $("#userdata .userdata_dsje").text(jshy.fDsje);
            $("#userdata .userdata_dslx").text(jshy.fDslx);
            return
          }
          console.warn('/APPapi/userinfo.do:', data.message)
        },
        error: function (error) {
          console.log(error);
        }
      })
    }

    function changeUserTag(id) {
      var r = /^\+?[1-9][0-9]*$/;
      if (r.test(id)) {
        var url = 'http://i.wsloan.com/w6h8y3_n17s4d/kh_bz.aspx?pid=' + id + '&hfkf=1&kfId=' + kfId;
        document.getElementById("nr").style.height = "750px";
        document.getElementById("nr").src = url;
      }
    }

    function changegroup(tid) {
      $("#J_demo").hide();
      $("#Tribe_" + tid).show().siblings().hide();
      $(".chat02").show();
      $("#tribels_" + tid).text(0);
      $("#tribels_" + tid).hide();
      getHistory();

      var li = $("#tribels_" + tid).parent()[0];
      var index = $(".chat03_content #grouplist li").index(li);
      $('.chat03_content #grouplist').prepend($('.chat03_content #grouplist li:eq(' + index + ')'));
      $("#grouplist").scrollTop(0);
    }

    function getHistory() {
      var nextkey = nextkeys.get('key_' + tribeid);
      WKIT.Conn.sdk.Tribe.getHistory({
        tid: tribeid,
        nextkey: nextkey,
        count: 10,
        success: function (data) {
          data = data.data;
          var list = data.msgs;
          console.log('获取群消息成功', data);
          list.forEach(function (item) {
            var fromuid = item.from.substring(8);
            var jshy = userlist['' + fromuid + ''];
            var userimg = picurl + "yhtx/no.jpg";
            var nickname = fromuid;
            if (jshy != undefined) {
              userimg = picurl + "yhtx/" + jshy.cHyYhtx;
              nickname = jshy.cHyNichen;
            } else if (fromuid == localUser.fUid) {
              userimg = picurl + "yhtx/" + localUser.cYhtx;
              nickname = localUser.cNichen;
            }

            var e = new Date(item.time),
              f = "";
            f += e.getFullYear() + "-", f += e.getMonth() + 1 + "-", f += e.getDate() + "  ", f += e.getHours() +
              ":", f += e.getMinutes() + ":", f += e.getSeconds();

            var msg = '';
            if (item.type == 0) {
              if (item.msg.length != 0)
                msg = ReplaceMsg(item.msg);
            } else if (item.type == 1) {
              msg = '<img class="tribemsgimage" style="height:200px;" src="' + item.msg + '"/>';
            }
            var i = '<div class="message clearfix"><div class="user-logo"><img src="' + userimg + '" />' +
              '</div>' +
              '<div class="wrap-text">' + '<h5 class="clearfix">' + nickname + '</h5>' + '<div>' + msg +
              '</div>' +
              '</div>' + '<div class="wrap-ri">' + '<div clsss="clearfix"><span>' + f + '</span></div>' +
              '</div>' +
              '<div style="clear:both;"></div>' + '</div>';
            $("#Tribe_" + tribeid).prepend(i), $("#Tribe_" + tribeid).scrollTop($("#Tribe_" + tribeid)[0].scrollHeight);
          });

          nextkey = data && data.nextKey;
          nextkeys.put('key_' + tribeid, nextkey);
        },
        error: function (error) {
          console.log('获取历史消息失败', error);
        }
      });
    }

    //
    function initproblem(key) {
      ajax({
        method: 'post',
        api: '/APPapi/problem.do',
        data: {
          searchkey: key
        },
        success: function (data) {
          $("#problem_ul").empty();
          if (data.content.length > 0) {
            data.content.forEach(function (item) {
              var li =
                '<li><a href="javascript:;" style="color:red;font-weight:bolder;" onclick="sendProblemLink(this)">' +
                item.ctitle + '</a><div title="搜索问题，单击标题发送QA方案给客户。">' + item.cContent + '</div><hr/></li>';
              $("#problem_ul").append(li);
            });
          }
        },
        error: function (e) {
          console.log(e);
        }
      });
    }

    function searchProblem() {
      var key = $("#problemSearchkey").val().trim();
      initproblem(key);
    }

    function sendProblemLink(dom) {
      //var url = "http://www.wsloan.com/help-list/#unknow#" + cla + "#" + id;
      var content = $(dom).next()[0].innerText;
      if (type == 0) {
        WKIT.sendMsg({
          msgType: 0,
          msg: content
        });
      } else if (type == 1) {
        var e = new Date,
          f = "";
        f += e.getFullYear() + "-", f += e.getMonth() + 1 + "-", f += e.getDate() + "  ", f += e.getHours() + ":", f +=
          e.getMinutes() + ":", f += e.getSeconds();
        var userimg = picurl + "yhtx/" + localUser.cYhtx;
        var nickname = localUser.cNichen;

        var i = '<div class="message clearfix"><div class="user-logo"><img src="' + userimg + '" />' + '</div>' +
          '<div class="wrap-text">' + '<h5 class="clearfix">' + nickname + '</h5>' + '<div>' + content + '</div>' +
          '</div>' + '<div class="wrap-ri">' + '<div clsss="clearfix"><span>' + f + '</span></div>' + '</div>' +
          '<div style="clear:both;"></div>' + '</div>';
        null != content && "" != content ? ($("#Tribe_" + tribeid).append(i),
          // $("#Tribe_" + tribeid).scrollTop($("#Tribe_" + tribeid)[0].scrollHeight), $("#textarea").val(""), message()
          $("#Tribe_" + tribeid).scrollTop($("#Tribe_" + tribeid)[0].scrollHeight), $("#textarea").val("")
        ) : alert("\u8bf7\u8f93\u5165\u804a\u5929\u5185\u5bb9!")

        WKIT.Conn.sdk.Tribe.sendMsg({
          tid: tribeid,
          msg: content,
          success: function (data) {
            console.log('发送群常见问题成功');
          },
          error: function (error) {
            console.log('发送群常见问题失败', error);
          }
        });
      }
    }

    //
    function saveChatHis(kfid, userid, msgid, content, time, type) {
      ajax({
        method: 'post',
        api: '/APPapi/chathis.do',
        data: {
          kfid: kfid,
          userid: userid,
          msgid: msgid,
          content: content,
          time: time,
          msgtype: type
        },
        error: function (e) {
          console.log(e);
        }
      });
    }

    function changetable2(index) {
      if (index == 0) {
        $("#usertag").hide();
        $("#problem").hide();
        $("#userdata").show();
      } else if (index == 1) {
        $("#userdata").hide();
        $("#problem").hide();
        $("#usertag").show();
      } else {
        $("#usertag").hide();
        $("#userdata").hide();
        $("#problem").show();
      }
    }


    Array.prototype.remove = function (s) {
      for (var i = 0; i < this.length; i++) {
        if (s == this[i])
          this.splice(i, 1);
      }
    }

    function Map() {
      /**
       * 存放键的数组
       * @type {Array}
       */
      this.keys = new Array();
      /**
       * 存放数据
       * @type {Object}
       */
      this.data = new Object();
      /**
       * 放入一个键值对
       * @param  {String} key
       * @param  {Object} value
       */
      this.put = function (key, value) {
        if (this.data[key] == null) {
          this.keys.push(key);
        }
        this.data[key] = value;
      };
      /**
       * 获取某键对应的值
       * @param  {String} key
       * @return {Object} value
       */
      this.get = function (key) {
        return this.data[key];
      };
      /**
       * 删除一个键值对
       * @param  {String} key
       */
      this.remove = function (key) {
        this.keys.remove(key);
        this.data[key] = null;
      };
      /**
       * 遍历Map，执行处理函数
       * @param  {Function}
       */
      this.each = function (fn) {
        if (typeof fn != 'function') {
          return;
        }
        var len = this.keys.length;
        for (var i = 0; i < len; i++) {
          var k = this.keys[i];
          fn(k, this.data[k], i);
        }
      };
      /**
       * 返回键值对数组
       * @return {Object} 键值对对象{key,value}的数组
       */
      this.entrys = function () {
        var len = this.keys.length;
        var entrys = new Array(len);
        for (var i = 0; i < len; i++) {
          var tmp = this.keys[i];
          entrys[i] = {
            key: tmp,
            value: this.data[tmp]
          };
        }
        return entrys;
      };
      /**
       * 判断Map是否为空
       * @return {Boolean}
       */
      this.isEmpty = function () {
        return this.keys.length == 0;
      };
      /**
       * 获取键值对数量
       * @return {Number}
       */
      this.size = function () {
        return this.keys.length;
      };
      /**
       * 重写toString
       * @return {String}
       */
      this.toString = function () {
        var s = "{";
        for (var i = 0; i < this.keys.length; i++, s += ',') {
          var k = this.keys[i];
          s += k + "=" + this.data[k];
        }
        s += "}";
        return s;
      };
    }
    // API
    // 获取用户本人的信息
    function getUserInfo() {
      ajax({
        api: '/APPapi/localUserInfo.do',
        method: 'get',
        data: {
          Imid: localUid
        },
        success: function (data) {
          if (data.state === 0) {
            localUser = data.content;
            asyncCount.value += 1;
            return
          }
          alert(data.message);
        },
        error: function (e) {
          console.log('localUserInfo.do(e):', e)
        }
      });
    }
    // 获取用户朋友们的信息
    function getFriendsInfo() {
      ajax({
        api: '/APPapi/getUserInfo.do',
        method: 'get',
        data: {
          Imid: localUid
        },
        success: function (data) {
          if (data.state === 0) {
            userlist = data.content.dicjson;
            mailHtml = data.content.mailHtml;
            asyncCount.value += 1;
            return
          }
          alert(data.message);
        },
        error: function (e) {
          console.log('getUserInfo.do(e):', e)
        }
      });
    }
    // 获取聊天室配置信息
    function getConfigInfo() {
      ajax({
        api: '/APPapi/getKey.do',
        method: 'get',
        success: function (data) {
          if (data.state === 0) {
            picurl = data.content.AliyunImagePath;
            appsecret = data.content.IMAppSecret;
            apppass = data.content.IMDefaultPWD;
            appkey = data.content.IMAppKey;
            asyncCount.value += 1;
            return
          }
          alert(data.message);
        },
        error: function (e) {
          console.log('getKey.do(e):', e)
        }
      });
    }

    // 以下为新添功能
    // 添加客户选项
    function changetable(index) {
      if (index == 0) {
        $("#khinfolist").hide();
        $("#maillist").hide();
        $("#grouplist").hide();
        $("#haoyoulist").show();
      } else if (index == 1) {
        $("#khinfolist").hide();
        $("#haoyoulist").hide();
        $("#grouplist").hide();
        $("#maillist").show();
      } else if (index == 2) {
        $("#khinfolist").hide();
        $("#haoyoulist").hide();
        $("#maillist").hide();
        $("#grouplist").show();
      } else {
        $("#haoyoulist").hide();
        $("#maillist").hide();
        $("#grouplist").hide();
        $("#khinfolist").show();
      }
    }

    // 添加Seachr按钮
    $('#khinfoSearch').click(SearchKfInfo);

    function SearchKfInfo() {
      $('#khinfolist li').remove();
      khpage = 1;
      initKhInfoList();
    }
    function initKhInfoList() {
      isInifkf = false;
      var skey = $("#khSearchKey").val();
      ajax({
        method: 'post',
        // async: false,
        api: "/APPapi/khinfo.do",
        data: {
          kfid: kfId,
          page: khpage,
          pageSize: khpagesize,
          searchKey: skey
        },
        success: function (data) {
          if (data.state == 0) {
            // var khlist = eval(data.msg);
            var khlist = data.content.data;
            // 客户列表
            khlist.length && khlist.forEach(function (item) {
              if (!document.getElementById("khls_" + item.id)) {

                var userimg = picurl + "yhtx/no.jpg";
                var nickname = item.cU_ser + " - " + item.id;

                var hyli = '<li>' +
                '<label class="online" ></label>' +
                '<a href="javascript:;">' +
                '<img src="' + userimg + '" />' +
                '</a>' +
                '<a href="javascript:;" class="chat03_name" data-id="' + item.id + '" >' +
                nickname + '</a>' +
                '<div class="nav-counter" id="hyls_' + item.id +
                '" style="display:none;">0</div></li>';
                $("#khinfolist").append(hyli);
              }
            });
            khpage++;
            isInifkf = true;
          }
        },
        error: function (error) {
          console.log(error);
        }
      });
    }

    /**********************以下为交互事件**************************/
    // 绑定元素事件
    $('.ct_3').click(function () {
      changetable(0);
    });
    $('.ct_5').click(function () {
      changetable(2);
    });
    $('.ct_4').click(function () {
      changetable(1);
    });
    $('.ct_6').click(function () {
      changetable(3);
    });
    $('.ct2_3').click(function () {
      changetable2(0);
    });
    $('.ct2_5').click(function () {
      changetable2(1);
    });
    $('.ct2_4').click(function () {
      changetable2(2);
    });
    // END

    // chat.js
    // (function (a) {
    //   a.extend({
    //     blinkTitle: {
    //       show: function () {
    //         var a = 0,
    //           b = document.title;
    //         if (-1 == document.title.indexOf("\u3010"))
    //           var c = setInterval(function () {
    //             a++, 3 == a && (a = 1), 1 == a && (document.title = "\u3010\u3000\u3000\u3000\u3011" + b),
    //               2 ==
    //               a && (document.title = "\u3010\u65b0\u6d88\u606f\u3011" + b)
    //           }, 500);
    //         return [c, b]
    //       },
    //       clear: function (a) {
    //         a && (clearInterval(a[0]), document.title = a[1])
    //       }
    //     }
    //   })
    // }(jQuery));

    // function message() {
    //   var a = $.blinkTitle.show();
    //   setTimeout(function () {
    //     $.blinkTitle.clear(a)
    //   }, 8e3)
    // };
    $(document).ready(function () {
      $(".chat03_content").on("mouseover", "li", function () {
        $(this).addClass("hover").siblings().removeClass("hover")
      }).mouseout(function () {
        $(this).removeClass("hover").siblings().removeClass("hover")
      });
      $(".chat03_content").on("click", ".personal li", function () {
        type = 0;
        var b = $(this).index() + 1;
        a = b, c = "img/head/20" + (12 + a) + ".jpg",
          d = $(this).find(".chat03_name").text(),
          $(this).addClass("choosed").siblings().removeClass("choosed"),
          $(".talkTo a").text($(this).children(".chat03_name").text());
        changeuser($(this).children(".chat03_name").attr("data-id"));
        return false;
      });
      $(".chat03_content").on("click", ".groupchat li", function () {
        if (tribeid != $(this).children(".chat03_name").attr("data-id") || type != 1) {
          type = 1;
          tribeid = $(this).children(".chat03_name").attr("data-id");
          var b = $(this).index() + 1;
          a = b, c = "img/head/20" + (12 + a) + ".jpg",
            d = $(this).find(".chat03_name").text(),
            $(this).addClass("choosed").siblings().removeClass("choosed"),
            $(".talkTo a").text($(this).children(".chat03_name").text())
          changegroup($(this).children(".chat03_name").attr("data-id"));
        }
        return false;
      });
      $(".wl_faces_box").on("mouseover", function () {
        $(".wl_faces_box").show()
      }).on("mouseout", function () {
        $(".wl_faces_box").hide()
      });
      $(".wl_faces_close").on("click", function () {
        $(".wl_faces_box").hide()
      });
      $(".wl_faces_main img").on("click", function () {
        var a = $(this).attr("src");
        $("#textarea").val($("#textarea").val() + "*#" + a.substr(a.indexOf("img/") + 4, 6) + "#*"),
          $("#textarea").focusEnd(),
          $(".wl_faces_box").hide()
      });
      $(".chat02_bar").on("click", "img", function () {
        sendMsg()
      });
      document.onkeydown = function (a) {
        if (type == 1) {
          var b = document.all ? window.event : a;
          return 13 == b.keyCode ? (sendMsg(), !1) : void 0
        }
      };
      $.fn.setCursorPosition = function (a) {
        return 0 == this.lengh ? this : $(this).setSelection(a, a)
      };
      $.fn.setSelection = function (a, b) {
        if (0 == this.lengh) return this;
        if (input = this[0], input.createTextRange) {
          var c = input.createTextRange();
          c.collapse(!0), c.moveEnd("character", b), c.moveStart("character", a), c.select()
        } else
          input.setSelectionRange && (input.focus(), input.setSelectionRange(a, b));
        return this
      };
      $.fn.focusEnd = function () {
        this.setCursorPosition(this.val().length)
      }
    });

    return entry();
  }
  // main();

  // html

</script>
<!--<script src="https://og6593g2z.qnssl.com/fundebug.0.0.7.min.js"-->

</html>
